<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Model {

  /**
   * @var string
   */
  protected $_table;
  /**
   * @var string
   */
  protected $_pk = 'id';
  /**
   * @var array
   */
  protected $_meta = array();
  /**
   * @var array 
   */
  protected static $_models = array();
  protected static $_dbs = array();

  /**
   *
   * @param create instance $name 
   * @return Model
   */
  public static function createInstance($name) {
    return new $name();
  }

  public static function getDb($name = 'default') {
    if (@self::$_dbs[$name] == NULL) {
      $config = array(
          'dbname' => 'startup_v1',
          'username' => 'root',
          'password' => '',
          'host' => 'localhost',
          'port' => 3306,
      );
      $db = self::$_dbs[$name] = new Database_Mysql($config);
    }
    return self::$_dbs[$name];
  }

  /**
   * 
   * @param  string  $name
   * @return Model
   */
  public static function getInstance($name) {
    if (NULL === @self::$_models[$name]) {
      self::$_models[$name] = self::createInstance($name);
    }

    return self::$_models[$name];
  }

  /**
   * @param Entity $entity 
   */
  public static function update($entity) {
    
  }

  /**
   *
   * @param Model_Entity $entity 
   */
  public static function insert($entity) {
    $model = str_replace('Entity','Model',get_class($entity));
    echo $model;
    $model = self::getInstance($model);
    return self::getDb()->insert($model, $entity);
  }

  public static function save($entity) {
//    return $entity->saved() ? self::update($entity) : self::insert($entity);
    return self::insert($entity);
  }

  /**
   *
   * @param   string|Model $model
   * @param   string|array $params 
   */
  public static function find($model, $params = NULL) {
    
  }

  /**
   *
   * @param   string|Model $model
   * @param   string|array $params 
   */
  public static function delete($entity) {
    
  }

  /**
   * @param   string  $name
   * @return  array
   */
  public function rules($name) {
    return @$this->_meta[$name]['rules'];
  }

  /**
   * @return array
   */
  public function field($name) {
    return $this->_meta[$name]['field'];
  }

  public function fields() {
    return $this->_meta;
  }

  public function inflect($name) {
    return str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
  }

  public function deflect($name) {
    return strtolower(preg_replace('/([a-z0-9])([A-Z])/', '\1_\2', $str));
  }

}
